﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Linq;
using MathematicallySafe.Base;
using StructureMap;

namespace HeadCounter.Armourer.Requesters
{
    public class Census: WebRequester
    {
        private readonly object _sync = new object();
        private readonly Queue<CharacterIdentity> _characterQueue = new Queue<CharacterIdentity>();

        public void EnqueueGetCharacter(CharacterIdentity identity)
        {
            lock (_sync)
            {
                if (!_characterQueue.Contains(identity))
                {
                    _characterQueue.Enqueue(identity);
                }
            }
        }

        public override ReqeusterDataType GetDataType()
        {
            return ReqeusterDataType.Character;
        }

        public override bool HasWork()
        {
            lock (_sync)
            {
                return _characterQueue.Count() > 0;
            }
        }

        public override XElement RequestData(BackgroundWorker worker)
        {
            CharacterIdentity identity;

            lock (_sync)
            {
                identity = _characterQueue.Dequeue();
            }

            worker.ReportProgress(0, "Downloading character " + identity.Name);
            return GetCharacter(identity);
        }

        private XElement GetCharacter(CharacterIdentity identity)
        {
            var uri = GetCharacterUri(identity);
            var xmlText = GetWebData(uri);

            XElement data = null;
            if (!string.IsNullOrEmpty(xmlText))
            {
                try
                {
                    data = XElement.Parse(xmlText).Element("characterInfo");
                }
                catch (Exception e)
                {
                    ObjectFactory.GetInstance<ILog<Census>>().Error("Error looking for characterInfo in XML : " + e.Message);
                }
            }

            return data;
        }

        private Uri GetCharacterUri(CharacterIdentity identity)
        {
            return new Uri(string.Format("http://{0}.wowarmory.com/character-sheet.xml?r={1}&cn={2}", identity.Region, identity.Realm, identity.Name));
        }
    }
}
